﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Space2D
{
    public class AABB : IEquatable<AABB>
    {
        public Vector2 Min { get; set; }
        public Vector2 Max { get; set; }
        public Vector2 Center
        {
            get
            {
                return (Min + Max) * 0.5f;
            }
        }

        public AABB()
        {
            Min = Vector2.zero;
            Max = Vector2.zero;
        }
        public AABB(Vector2 min, Vector2 max)
        {
            Min = min;
            Max = max;
        }

        public void RefreshAABB(Vector2 min, Vector2 max)
        {
            Min = min;
            Max = max;
        }

        public bool IntersectsAABB(AABB aabb)
        {
            bool xIntersects = (Max.x > aabb.Min.x) && (Min.x < aabb.Max.x);
            bool yIntersects = (Max.y > aabb.Min.y) && (Min.y < aabb.Max.y);
            return xIntersects && yIntersects;
        }

        public bool Equals(AABB other)
        {
            return Min == other.Min && Max == other.Max;
        }

        public void ExpandBy(AABB b)
        {
            Vector3 min = Min;
            Vector3 max = Max;
            if (b.Min.x < Min.x) { min.x = b.Min.x; }
            if (b.Min.y < Min.y) { min.y = b.Min.y; }
            if (b.Max.x > Max.x) { max.x = b.Max.x; }
            if (b.Max.y > Max.y) { max.y = b.Max.y; }
            Min = min;
            Max = max;
        }

        public static AABB AABBByPoly(List<Vector2> poly)
        {
            AABB aabb = new AABB();
            float minX = float.MaxValue;
            float minY = float.MaxValue;
            float maxX = float.MinValue;
            float maxY = float.MinValue;
            for (int i = 0; i < poly.Count; i++)
            {
                Vector2 v2 = poly[i];
                minX = Mathf.Min(minX, v2.x);
                minY = Mathf.Min(minY, v2.y);
                maxX = Mathf.Max(maxX, v2.x);
                maxY = Mathf.Max(maxY, v2.y);
            }
            aabb.Min = new Vector2(minX, minY);
            aabb.Max = new Vector2(maxX, maxY);
            return aabb;
        }

        public List<Vector2> AABB2Points()
        {
            List<Vector2> points = new List<Vector2>() { new Vector2(Min.x, Max.y), new Vector2(Max.x, Max.y), new Vector2(Max.x, Min.y), new Vector2(Min.x, Min.y) };
            return points;
        }
    }
}